package com.ruoyi.material.service.impl;

import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.material.domain.SysMaterial;
import com.ruoyi.material.mapper.SysMaterialMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.material.mapper.SysUserMaterialMapper;
import com.ruoyi.material.domain.SysUserMaterial;
import com.ruoyi.material.service.ISysUserMaterialService;

/**
 * 资料评分Service业务层处理
 * 
 * @author hsx
 * @date 2022-01-09
 */
@Service
public class SysUserMaterialServiceImpl implements ISysUserMaterialService 
{
    @Autowired
    private SysUserMaterialMapper sysUserMaterialMapper;

    @Autowired
    private SysMaterialMapper sysMaterialMapper;

    /**
     * 查询资料评分
     * @param userId
     * @param materialId
     * @return
     */
    @Override
    public SysUserMaterial selectSysUserMaterialById(Long userId,Long materialId)
    {
        return sysUserMaterialMapper.selectSysUserMaterialById(userId,materialId);
    }

    /**
     * 查询资料评分列表
     * 
     * @param sysUserMaterial 资料评分
     * @return 资料评分
     */
    @Override
    public List<SysUserMaterial> selectSysUserMaterialList(SysUserMaterial sysUserMaterial)
    {
        //获取当前用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 加入当前用户id
        sysUserMaterial.setUserId(user.getUserId());
        return sysUserMaterialMapper.selectSysUserMaterialList(sysUserMaterial);
    }

    /**
     * 新增资料评分
     * @param list
     * @param materialId
     * @return
     */
    @Override
    public int insertSysUserMaterial(List<Long> list,Long materialId)
    {
        return sysUserMaterialMapper.insertSysUserMaterial(list,materialId);
    }

    /**
     * 修改资料评分
     * 
     * @param sysUserMaterial 资料评分
     * @return 结果
     */
    @Override
    public int updateSysUserMaterial(SysUserMaterial sysUserMaterial)
    {
        // 查询更新前状态
        SysUserMaterial oldSysUserMaterial = sysUserMaterialMapper.selectSysUserMaterialById(sysUserMaterial.getUserId(), sysUserMaterial.getMaterialId());
        // 更新分数
        int res = sysUserMaterialMapper.updateSysUserMaterial(sysUserMaterial);

        // 更新Material 总分数和平均人数
        SysMaterial sysMaterial = sysMaterialMapper.selectSysMaterialByMaterialId(sysUserMaterial.getMaterialId());
        sysMaterial.setScore(sysMaterial.getScore()+sysUserMaterial.getScore()-oldSysUserMaterial.getScore());
        if(oldSysUserMaterial.getScore() == 0){
            sysMaterial.setNumber(sysMaterial.getNumber()+1);
        }
        sysMaterialMapper.updateSysMaterial(sysMaterial);

        return res;
    }

}
